package nku.csc660;

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

@SuppressWarnings("serial")
public class IMClient extends JFrame implements ActionListener
{

	private Client client;
	private String userName;
    private JTextArea  messages;
    private JTextField input;
    private JButton buttonSend;
    private JButton buttonExit;
    private JButton buttonSend1;
    private JButton buttonWho;
    private MessagesThread thread; 

	public IMClient(String userName)
	{
		super(userName);
		this.userName = userName;
		client = new Client();
		if(!connectionEstablished())
		{
			System.exit(1);
		}

		buildGUI();
		thread = new MessagesThread();
		thread.start();
	}

	private boolean connectionEstablished()
	{
		if(client.isConnected()){
			client.sendMessage("Do you have room for me?");
			try {
				String temp = client.readLine();
				System.out.println(temp);

				if(temp.equals("YES")){
					temp = client.readLine();
					System.out.println(temp);
					if(temp.equals("What is your name?")){
						client.sendMessage(userName);
					}
					else{
						return false;
					}
					System.out.println("I was here...");
					return true;
				}
				else{
					JOptionPane.showMessageDialog(null, "Server doesn't have room for you, Try Again Later!");
					return false;
				}
			} catch (IOException e) {
				return false;
			}
		}
		else{
			JOptionPane.showMessageDialog(null,"Couldn't connect to Server!");
			return false;
		}
	}

	private void buildGUI()
	{
        buttonSend = new JButton("Send");
        buttonSend1 = new JButton("Send to User");
        buttonWho = new JButton("Who");
        buttonExit = new JButton("Exit");


        messages = new JTextArea();
        messages.setRows(10);
        messages.setColumns(50);
        messages.setEditable(false);
        input  = new JTextField(50);
        JScrollPane scrollPane = new JScrollPane(messages, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        add(scrollPane,"Center");
        JPanel inputPanel = new JPanel(new FlowLayout());
        inputPanel.add(input);
        inputPanel.add(buttonSend);
        inputPanel.add(buttonSend1);
        inputPanel.add(buttonWho);
        inputPanel.add(buttonExit);
        add(inputPanel,"South");
        buttonSend.addActionListener(this);
        buttonExit.addActionListener(this);
        buttonSend1.addActionListener(this);
        buttonWho.addActionListener(this);
        setSize(500,300);
        setVisible(true);
        pack();
	}

	public static void main(String... args)
	{
		String userName = JOptionPane.showInputDialog(null, "Please enter your username : ", "", 1);
		@SuppressWarnings("unused")
		IMClient userInstance = new IMClient(userName);
	}

	public boolean isConnected()
	{
		return client.isConnected();
	}

	public void setUserName(String userName)
	{
		this.userName = userName;
	}

	public String getUserName()
	{
		return userName;
	}

	public void actionPerformed(ActionEvent e)
	{
        if ( e.getSource() == buttonExit )
        {
            exit();
        }
        else if(e.getSource() == buttonSend)
        {
        	sendMessage(input.getText());
        }
        else if(e.getSource() == buttonSend1)
        {
        	sendMessage1(input.getText());
        }
        else if(e.getSource() == buttonWho)
        {
        	sendWho();
        }
	}

	private void sendMessage(String lines)
	{
		client.sendMessage("@SEND");
		client.sendMessage(lines);
		client.sendMessage("@DONE");
	}

	@SuppressWarnings("deprecation")
	private void exit()
	{
		client.sendMessage("@LOGOUT");
	}

	private void sendMessage1(String lines)
	{
    	String userName1 = JOptionPane.showInputDialog(null, "Please enter username to send to : ", "", 1);
		client.sendMessage("@SEND-USER: " + userName1);
		client.sendMessage(lines);
		client.sendMessage("@DONE");
	}

	private void sendWho(){
		client.sendMessage("@WHO");
	}

    class  MessagesThread extends Thread
    {
        public void run()
        {
            String line;
            try
            {
                while(true)
                {
                    line = client.readLine();
                    messages.append(line + "\n");
                    if(line.equals("Server is closing all connections!")){
                    	line = client.readLine();
                    	messages.append(line+ "\n");
                    	client.cleanUp();
                    	break;
                    }
                }
            }
            catch(IOException ex)
            {
            	messages.append("Problem Connecting to IM Server, Please Reconnect!");
            	System.out.println(ex);
            }
        }
    }
}
